package com.aos.erp.fs.show;

import com.aos.erp.fs.enums.FileStatus;
import com.aos.erp.fs.model.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.List;


@Slf4j
@Component
public class FileViewResolver {

    @Resource
    private List<FileView> fileViewList;

    public void show(HttpServletRequest request, HttpServletResponse response, SysFile file, ViewType type) {

        if (this.preFilter(request, response, file)) {
            return;
        }

        if (fileViewList != null) {
            for (FileView fileView : fileViewList) {
                //简单的决策处理
                if (fileView.getUriType() == file.getUriType()) {
                    this.typeHandle(request, response, file, type);
                    fileView.render(request, response, file);
                    break;
                }
            }
        }

    }

    private void typeHandle(HttpServletRequest request, HttpServletResponse response, SysFile file, ViewType type) {

        if (type == ViewType.download) {
            //设置下载的名称，地址
            String fileName = null;
            try {
                fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString());
                response.setContentType("application/octet-stream");//设置文件类型
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "");
            } catch (UnsupportedEncodingException e) {
                log.error("系统不支持UTF-8");
            }

        } else {
            response.setContentType(file.getContentType());//设置文件类型
        }
    }

    private boolean preFilter(HttpServletRequest request, HttpServletResponse response, SysFile file) {
        //过滤删除掉的文件和过期文件
        if (file.getStatus() == FileStatus.del) {
            // 404
            fileNotFound(request, response);
            return true;
        } else if (file.getTimeOutTime() != null
                && Calendar.getInstance().getTime().after(file.getTimeOutTime())) {
            //文件已过期
            fileNotFound(request, response);
            return true;
        }


        return false;
    }

    private void fileNotFound(HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(404);
    }
}